package com.caldremch.myhttp.convert;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author Caldremch
 * @date 2018-09-03 15:59
 * @describe
 **/

/**
 *
 * @param <T> 具体Type
 */
final class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson mGson;
    private final TypeAdapter<T> mAdapter;
    private final JsonParser mJsonParser;

    MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.mAdapter = adapter;
        this.mJsonParser = new JsonParser();

    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String response = value.string();

        JsonObject jsonObject = mJsonParser.parse(response).getAsJsonObject();

        JsonElement dataEle = jsonObject.get("data");


        if (dataEle != null) {
            try {

                String dataStr = jsonObject.get("data").getAsString();
                JsonObject jsonDataElementObj = mJsonParser.parse(dataStr).getAsJsonObject();
                jsonObject.add("data", jsonDataElementObj);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        String finalJsonStr = mGson.toJson(jsonObject);
        MediaType contentType = value.contentType();
        Charset charset;
        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF-8"));
        } else {
            charset = Charset.forName("UTF-8");
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(finalJsonStr.getBytes());
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = mGson.newJsonReader(reader);
        try {
            return mAdapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
